package com.example.repository;

import com.example.model.QualityCheck;
import com.example.model.LaundryOrder;
import com.example.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface QualityCheckRepository extends JpaRepository<QualityCheck, Long> {
    
    // 根据订单查找质检记录
    Optional<QualityCheck> findByOrder(LaundryOrder order);
    
    // 根据质检员查找记录
    Page<QualityCheck> findByInspector(User inspector, Pageable pageable);
    
    // 根据质检结果查找
    List<QualityCheck> findByResult(QualityCheck.QualityResult result);
    
    // 查找需要返工的质检记录
    List<QualityCheck> findByNeedsReworkTrue();
    
    // 根据时间范围查找质检记录
    @Query("SELECT qc FROM QualityCheck qc WHERE qc.checkedAt BETWEEN :startDate AND :endDate")
    List<QualityCheck> findByDateRange(LocalDateTime startDate, LocalDateTime endDate);
    
    // 统计各质检结果数量
    @Query("SELECT qc.result, COUNT(qc) FROM QualityCheck qc GROUP BY qc.result")
    List<Object[]> countByResult();
    
    // 统计质检员的工作量
    @Query("SELECT qc.inspector, COUNT(qc) FROM QualityCheck qc GROUP BY qc.inspector")
    List<Object[]> countByInspector();
    
    // 查找今日质检记录
    @Query("SELECT qc FROM QualityCheck qc WHERE qc.checkedAt >= :startOfDay AND qc.checkedAt < :endOfDay")
    List<QualityCheck> findTodayQualityChecks(@Param("startOfDay") LocalDateTime startOfDay, @Param("endOfDay") LocalDateTime endOfDay);
    
    // 计算平均质检分数
    @Query("SELECT AVG(qc.overallScore) FROM QualityCheck qc WHERE qc.checkedAt >= :startDate")
    Double getAverageQualityScore(LocalDateTime startDate);
    
    // 查找高质量订单（评分>=9）
    @Query("SELECT qc FROM QualityCheck qc WHERE qc.overallScore >= 9")
    List<QualityCheck> findHighQualityOrders();
}
